// 访客统计API客户端
class VisitorAnalytics {
    constructor() {
        this.baseUrl = '/api/visitor/analytics';
        this.cache = new Map();
        this.cacheTimeout = 300000; // 5分钟缓存
    }

    // 获取访客统计摘要
    async getSummary(startDate, endDate) {
        const cacheKey = `summary_${startDate}_${endDate}`;
        const cached = this.getCachedData(cacheKey);
        if (cached) return cached;

        try {
            const params = new URLSearchParams({ start_date: startDate, end_date: endDate });
            const response = await fetch(`${this.baseUrl}/summary?${params}`);
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            const data = await response.json();
            this.setCachedData(cacheKey, data, this.cacheTimeout);
            return data;
        } catch (error) {
            console.error('获取访客统计摘要失败:', error);
            throw error;
        }
    }

    // 获取热门页面
    async getTopPages(startDate, endDate, limit = 10) {
        const cacheKey = `top_pages_${startDate}_${endDate}_${limit}`;
        const cached = this.getCachedData(cacheKey);
        if (cached) return cached;

        try {
            const params = new URLSearchParams({ 
                start_date: startDate, 
                end_date: endDate, 
                limit: limit.toString() 
            });
            const response = await fetch(`${this.baseUrl}/top-pages?${params}`);
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            const data = await response.json();
            this.setCachedData(cacheKey, data, this.cacheTimeout);
            return data;
        } catch (error) {
            console.error('获取热门页面失败:', error);
            throw error;
        }
    }

    // 获取地理分布
    async getGeoDistribution(startDate, endDate) {
        const cacheKey = `geo_${startDate}_${endDate}`;
        const cached = this.getCachedData(cacheKey);
        if (cached) return cached;

        try {
            const params = new URLSearchParams({ start_date: startDate, end_date: endDate });
            const response = await fetch(`${this.baseUrl}/geo-distribution?${params}`);
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            const data = await response.json();
            this.setCachedData(cacheKey, data, this.cacheTimeout);
            return data;
        } catch (error) {
            console.error('获取地理分布失败:', error);
            throw error;
        }
    }

    // 获取设备统计
    async getDeviceStats(startDate, endDate) {
        const cacheKey = `device_${startDate}_${endDate}`;
        const cached = this.getCachedData(cacheKey);
        if (cached) return cached;

        try {
            const params = new URLSearchParams({ start_date: startDate, end_date: endDate });
            const response = await fetch(`${this.baseUrl}/device-stats?${params}`);
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            const data = await response.json();
            this.setCachedData(cacheKey, data, this.cacheTimeout);
            return data;
        } catch (error) {
            console.error('获取设备统计失败:', error);
            throw error;
        }
    }

    // 获取实时统计
    async getRealTimeStats(hours = 24) {
        const cacheKey = `realtime_${hours}`;
        const cached = this.getCachedData(cacheKey);
        if (cached) return cached;

        try {
            const params = new URLSearchParams({ hours: hours.toString() });
            const response = await fetch(`${this.baseUrl}/realtime?${params}`);
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            const data = await response.json();
            this.setCachedData(cacheKey, data, 60000); // 实时数据缓存1分钟
            return data;
        } catch (error) {
            console.error('获取实时统计失败:', error);
            throw error;
        }
    }

    // 缓存管理
    getCachedData(key) {
        const cached = this.cache.get(key);
        if (cached && Date.now() - cached.timestamp < cached.timeout) {
            return cached.data;
        }
        this.cache.delete(key);
        return null;
    }

    setCachedData(key, data, timeout) {
        this.cache.set(key, {
            data: data,
            timestamp: Date.now(),
            timeout: timeout
        });
    }

    // 清除缓存
    clearCache() {
        this.cache.clear();
    }
}

// 创建全局实例
const visitorAnalytics = new VisitorAnalytics();